package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.Service.MemberService;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 处理会员相关操作
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;


    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        //获取页面输入的手机号码
        String telephone = (String) map.get("telephone");
        //取出Redis中保存的验证码
        String s = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //获取页面用户输入的验证码
        String validateCode = (String) map.get("validateCode");
        //将Redis中保存的验证码s和用户传过来的验证码进行比较
        if (s!=null && validateCode!=null&& s.equals(validateCode)){
            //验证码输入正确
            //判断当前用户是否为会员，查询会员表
            Member member = memberService.findByTelephone(telephone);
            if (member == null){
                //member为空则用户不是会员，自动注册（将用户信息保存到会员表中）
                member=new Member();
                member.setRegTime(new Date());//设置注册时间
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //到这里则登入成功
            //向客户端浏览器写入Cookie,内容为手机号
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60*60*24*30);//设置有效期
            response.addCookie(cookie);//将Cookie写入浏览器

            //将会员信息保存到Redis
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,360000,json);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else {
            //对比验证码失败，返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
